import {ref} from 'vue'
import type {ConsultOrderItem, FollowType} from '@/types/consult'
import {cancelOrder, deleteOrder, followOrUnfollow, getPrescriptionPic} from '@/services/consult'
import { showImagePreview, showToast } from 'vant'
import { OrderType } from '@/enums'
import type { OrderDetail } from '@/types/order'
import { onMounted } from 'vue'
import { getMedicalOrderDetail } from '@/services/order'

export const useFollew=(type:FollowType='doc')=>{
    const loading=ref(false)
    const follow=async (item:{id:string,likeFlag: 0 | 1})=>{
        loading.value=true
        try {
            await followOrUnfollow(item.id,type)
            item.likeFlag=item.likeFlag===0 ? 1 :0
        }finally{
            loading.value=false
        }
        
    }
    return {loading,follow}
}


// 查看处方
export const useShowPrescription =()=>{
    const showPrescriptionPic=async (id?:string)=>{
        if (id){
            const res=  await getPrescriptionPic(id)
            showImagePreview([res.data.url])
        }
    
    }
    return {showPrescriptionPic}
}


export const useCancelOrder=()=>{
    
// 取消订单
    const loading=ref(false)
    const cancelConsultOrder =async (item:ConsultOrderItem)=>{
        try {
            loading.value=true
            await cancelOrder(item.id)
            item.status=OrderType.ConsultCancel
            item.statusValue='已取消'
            showToast('取消订单成功')
        } catch (error) {
            showToast('取消订单失败')
        } finally{
            loading.value=false
        }
    }
    return {loading,cancelConsultOrder}
}

export const useDeleteOrder=(cb:()=>void)=>{
    // 删除订单
    const delloading=ref(false)
    const deleteConsultOrder=async (item:ConsultOrderItem)=>{
        try {
            delloading.value=true
            await deleteOrder(item.id)
            cb && cb()
            showToast('删除成功')
        } catch (error) {
            showToast('删除失败')
        }finally{
            delloading.value=false
        }
    }
    return {delloading,deleteConsultOrder}

}


export const useOrederDetail=(id:string)=>{
    const order=ref<OrderDetail>()
    const loading=ref(false)
    onMounted(async () => {
        loading.value=true
        try {
            const res=await getMedicalOrderDetail(id)
            order.value=res.data
        } finally{
            loading.value=false
        }
    })
    return {loading,order}
}